﻿using Arch.EntityFrameworkCore.UnitOfWork;
using AutoMapper;
using MyTodoApi.Context;
using Shared.ToDo.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyTodoApi.Services
{
    public class UserService : BaseService<UserDto, User>, IUserService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;

        public UserService(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper)
        {
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
        }

        new public async Task<ApiResponse> UpdateAsync(UserDto userDto)
        {
            try
            {
                var user = mapper.Map<User>(userDto);
                var repository = unitOfWork.GetRepository<User>();
                var userEntity = await repository.GetFirstOrDefaultAsync(predicate: x => x.ID.Equals(user.ID));
                if (userEntity != null)
                {
                    userEntity.Account = user.Account;
                    userEntity.PassWord = user.PassWord;
                    userEntity.UserName = user.UserName;
                    userEntity.UpdateTime = DateTime.Now;
                }
                repository.Update(userEntity);
                var result = await unitOfWork.SaveChangesAsync();
                if (result > 0)
                {
                    return new ApiResponse(true, userEntity);
                }
                else
                {
                    return new ApiResponse(false, "保存失败");
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse(false, ex.Message);
            }
        }
    }
}
